import React, { Component } from 'react'
import MyNavBar from '../../components/MyNavBar'
import styles from './index.module.scss'

import { getCityList, getHotCityList } from '../../api/city'
import { getCurrentCity, setLocalCity } from '../../utils/city'
import { AutoSizer, List} from 'react-virtualized';
import { Toast } from 'antd-mobile'

const TITLE_HEIGHT = 36
const CITY_HEIGHT = 50
const HASDATA = ['北京','上海','广州','深圳']

export default class CityList extends Component {
  constructor () {
    super()

    this.state = {
      cityListObj: null, // 城市列表对象
      cityIndexList: null, // 右边的城市索引数组
      selectedIndex: 0 // 选中的索引
    }
  }
  // 创建ref，用来操作dom,通过ref属性绑定在<List />上
  listRef = React.createRef()

  componentDidMount () {
    this.dealCityListData()
  }

  dealCityListData = async () => {
    // a-z城市
    const res1 = await getCityList()
    console.log('getCityListData', res1);

    const tempObj = {}
    let tempIndexList = []
    res1.data.body.forEach(item => {
      const letter = item.short.substr(0,1)
      // 按照城市首字母a-z把城市进行分组
      if (tempObj[letter]) {
        tempObj[letter].push(item)
      } else {
        tempObj[letter] = [item]
      }
    });

    tempIndexList = Object.keys(tempObj).sort()

    // 热门城市
    const res2 = await getHotCityList()
    tempObj['hot'] = res2.data.body
    tempIndexList.unshift('hot')

    // 定位城市
    const res3 = await getCurrentCity()
    tempObj['#'] = [res3]
    tempIndexList.unshift('#')

    console.log('tempObj:tempIndexList:',tempObj,tempIndexList);

    this.setState({
      cityListObj:tempObj,
      cityIndexList:tempIndexList
    })
  }

  // 格式化标题字母
  formaTitle = letter => {
    switch (letter) {
      case '#':
        return '定位城市'
      case 'hot':
        return '热门城市'
      default:
        return letter.toUpperCase()
    }
  }

  // 点击右边索引，自动切换选中索引
  // 实现原理就是直接让左侧列表滚动,且控制顶部对齐：scrollToAlignment='start'
  toggleSelect = index => {

    this.listRef.current.scrollToRow(index)
  }

  // 切换城市
  toggleCitySelect = ({label,value}) => {
    
    if (!HASDATA.includes(label)) {
      Toast.info('该城市暂无房源～',1)
      return 
    }
    // 保存到本地，关闭当前页面
    setLocalCity({label,value})
    this.props.history.goBack()
  }

  // 左侧城市列表
  rowRenderer = ({
    key, // Unique key within array of rows
    index, // Index of row within collection
    isScrolling, // The List is currently being scrolled
    isVisible, // This row is visible within the List (eg it is not an overscanned row)
    style // Style object to be applied to row (to position it)
  }) => {
    const {cityListObj, cityIndexList} = this.state
    const letter = cityIndexList[index]
    const list = cityListObj[letter]
    return (
      // style={style}一定不能少,复用就靠position的top值改变实现
      <div key={key} style={style} className={styles.city}>
        <div className={styles.title}>{this.formaTitle(letter)}</div>
        {<div>{list.map(item=>{
          return (<div 
          onClick={()=> this.toggleCitySelect(item)}
          className={styles.name} 
          key={item.value}>
            {item.label}
            </div>)
        })}</div>}
      </div>
    );
  }

  // 每行的行高
  calcRowHeight = ({ index }) => {
    const { cityIndexList, cityListObj } = this.state
    const letter = cityIndexList[index]
    const list = cityListObj[letter]
    return TITLE_HEIGHT + list.length * CITY_HEIGHT
  }

  // 渲染右侧索引
  renderCityIndexList = () => {
    const { cityIndexList, selectedIndex } = this.state
    return (
      <div className={styles.cityIndex}>
        {cityIndexList.map((item,index) => {
          return (
            <div 
            // 点击右侧索引，传递索引
            onClick={()=> this.toggleSelect(index)}
            className={styles.cityIndexItem}
            key={item}>
              <span 
              className={selectedIndex===index ? styles.indexActive:''}
              >
                {item==='hot'?'热':item.toUpperCase()}
              </span>
            </div>
          )
        })}
      </div>
    )
  }

  // 获取左侧城市列表的滚动索引,将滚动索引赋值给右侧选中索引
  onRowsRendered = ({startIndex}) => {
    console.log('startIndex', startIndex);
    if (startIndex !== this.state.selectedIndex) {
      this.setState({
        selectedIndex: startIndex
      })
    }
  }

  render() {
    const { cityIndexList } = this.state
    return (
      <div className={styles.citylist}>
        <MyNavBar>城市选择</MyNavBar>
        {/* 渲染左侧城市列表 */}
        {/* 使用AutoSizer获取屏幕宽高时，父组件的宽高必须是100% */}
        {cityIndexList && (
          <AutoSizer>
          {({height, width}) => (
          <List
          // style={{background:'pink'}}
            ref={this.listRef}
            width={width}
            height={height - 45}
            rowCount={cityIndexList.length}
            rowHeight={this.calcRowHeight}
            rowRenderer={this.rowRenderer}
            onRowsRendered={this.onRowsRendered}
            scrollToAlignment='start'
          />
        )}
        </AutoSizer>
        )}
        {/* 渲染右边的索引 */}
        {cityIndexList && this.renderCityIndexList()}
      </div>
    )
  }
}
